package com.yycx.module.bus.provider.service.impl;

import cn.hutool.core.map.MapUtil;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yycx.common.base.entity.EntityMap;
import com.yycx.common.base.utils.FlymeUtils;
import com.yycx.common.constants.CommonConstants;
import com.yycx.common.mybatis.base.service.impl.BaseServiceImpl;
import com.yycx.common.mybatis.model.ResultBody;
import com.yycx.common.mybatis.query.CriteriaQuery;
import com.yycx.common.mybatis.query.CriteriaSave;
import com.yycx.common.mybatis.query.CriteriaUpdate;
import com.yycx.common.security.OpenHelper;
import com.yycx.common.security.OpenUser;
import com.yycx.common.utils.ApiAssert;
import com.yycx.module.admin.provider.mapper.BaseUserDeptMapper;
import com.yycx.module.bus.client.entity.BusDept;
import com.yycx.module.bus.client.entity.hy.BusDeptHy;
import com.yycx.module.bus.client.entity.BusSaleman;
import com.yycx.module.bus.provider.mapper.BusDeptMapper;
import com.yycx.module.bus.provider.service.hy.BusDeptHyService;
import com.yycx.module.bus.provider.service.BusDeptService;
import com.yycx.module.bus.provider.service.BusSalemanService;
import com.yycx.module.bus.provider.service.hy.HyRemoteOrderService;
import com.yycx.module.system.client.entity.SysCompany;
import com.yycx.module.system.client.entity.SysOrganization;
import com.yycx.module.system.provider.service.SysCompanyService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * 部门接口实现类
 *
 * @author flyme
 * @date 2020-07-28
 */
@Service
@DSTransactional
public class BusDeptServiceImpl extends BaseServiceImpl<BusDeptMapper, BusDept> implements BusDeptService {


    @Resource
    private SysCompanyService companyService;

    @Resource
    private BaseUserDeptMapper userDeptMapper;

    @Resource
    private HyRemoteOrderService hyRemoteOrderService;

    @Resource
    private BusSalemanService salemanService;

    @Resource
    private BusDeptHyService deptHyService;

    @Override
    public ResultBody beforeAdd(CriteriaSave cs, BusDept dept, EntityMap extra) {
        Integer isFlp = cs.getInt("isFlp", 0);
        CriteriaQuery cq = new CriteriaQuery(BusDept.class);
        Long companyId = OpenHelper.getCompanyId();
        SysCompany company = companyService.getById(companyId);
        Long organizationId = company.getOrganizationId();
        Long n = count(cq.eq(true, "deptName", dept.getDeptName()).eq(true, "companyId", companyId).eq(true, "organizationId", organizationId));
        ApiAssert.lezero("部门名称已存在", n.intValue());
        dept.setDeptState(CommonConstants.ENABLED);
        dept.setOrganizationId(organizationId);
        if (isFlp.equals(1)) {
            dept.setCompanyId(5L);
        } else {
            dept.setCompanyId(companyId);
        }
        Long saleManId = dept.getSalemanId();
        if (FlymeUtils.isNotEmpty(saleManId)) {
            BusSaleman saleMan = salemanService.getById(saleManId);
            dept.setSaleManName(saleMan.getSaleManName());
        }
        return ResultBody.ok();
    }

    @Override
    public ResultBody beforeEdit(CriteriaUpdate<BusDept> cu, BusDept busDept, EntityMap extra) {
        Long saleManId = busDept.getSalemanId();
        if (FlymeUtils.isNotEmpty(saleManId)) {
            BusSaleman saleMan = salemanService.getById(saleManId);
            busDept.setSaleManName(saleMan.getSaleManName());
        }
        return super.beforeEdit(cu, busDept, extra);
    }

    @Override
    public ResultBody afterEdit(CriteriaUpdate cu, BusDept dept, EntityMap extra) {
        Integer proLevel = FlymeUtils.getInteger(dept.getProLevel(), 0);
        salemanService.updateProLevel(proLevel, dept.getDeptId());
        return super.afterEdit(cu, dept, extra);
    }

    @Override
    public ResultBody afterAdd(CriteriaSave cs, BusDept busDept, EntityMap extra) {
        //TODO 同步部门到海鹰系统
        return super.afterAdd(cs, busDept, extra);
    }

    @Override
    public ResultBody beforeListEntityMap(CriteriaQuery<BusDept> cq, BusDept dept, EntityMap requestMap) {
        Integer auth = cq.getInt("auth", 0);
        Integer isFlp = cq.getInt("isFlp", 0);
        OpenUser openUser = OpenHelper.getUser();
        if (isFlp.equals(1)) {
            cq.eq(BusDept.class, "companyId", 5);
        } else {
            cq.eq(BusDept.class, "companyId", openUser.getCompanyId());
        }
        cq.eq(BusDept.class, "deptState", CommonConstants.ENABLED);
        if (auth.equals(CommonConstants.INT_1)) {
            Long userId = openUser.getUserId();
            List<Long> deptIds = userDeptMapper.selectUserDeptIds(userId);
            if (FlymeUtils.isNotEmpty(deptIds)) {
                cq.in("deptId", deptIds);
            }
        }
        cq.createJoin(SysCompany.class);
        cq.orderByAsc("deptCode");
        return super.beforeListEntityMap(cq, dept, requestMap);
    }


    @Override
    public List<BusDept> listByCompanyId(Map params) {
        String deptType = MapUtil.getStr(params, "deptType");
        CriteriaQuery cq = new CriteriaQuery(BusDept.class);
        cq.eq(FlymeUtils.isNotEmpty(deptType), "deptType", deptType);
        cq.eq(true, "companyId", 5L);
        cq.eq(true, "deptState", CommonConstants.INT_1);
        cq.orderByAsc("orderNum");
        return list(cq);
    }

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public ResultBody beforePageList(CriteriaQuery<BusDept> cq, BusDept dept, EntityMap requestMap) {
        Integer deptState = cq.getInt("deptState", 1);
        String deptName = cq.getParams("deptName");
        cq.select(BusDept.class, "*");
        cq.addSelect(SysCompany.class, "companyName");
        cq.addSelect(SysOrganization.class, "organizationName");
        cq.addSelect(BusSaleman.class, "saleManName");
        cq.eq(BusDept.class, "deptState", deptState);
        if (FlymeUtils.isNotEmpty(deptName)) {
            cq.and(e -> e.like("deptName", deptName).or().like("deptCode", deptName));
        }
        cq.eq(BusDept.class, "deptType");
        cq.eq(BusDept.class, "organizationId");
        cq.createJoin(SysCompany.class);
        cq.createJoin(BusSaleman.class);
        cq.createJoin(SysOrganization.class);
        cq.orderByAsc("deptCode");
        return ResultBody.ok();
    }

    @Override
    public ResultBody setSaleMan(Long saleManId, Long deptId) {
        CriteriaUpdate cu = new CriteriaUpdate();
        cu.set(true, "saleManId", saleManId);
        cu.eq(true, "deptId", deptId);
        Boolean result = update(cu);
        return ResultBody.ok(result);
    }

    @Override
    public BusDept getByDeptName(String deptName, Long companyId) {
        return getOne(new QueryWrapper<BusDept>().lambda().eq(true, BusDept::getCompanyId, companyId).like(BusDept::getDeptName, deptName));
    }

    @Override
    public BusDept getByDeptName(String deptName) {
        return getOne(new QueryWrapper<BusDept>().lambda().eq(BusDept::getDeptName, deptName));
    }

    @Override
    public BusDept getByDeptCode(String deptCode, Long companyId) {
        return getOne(new QueryWrapper<BusDept>().lambda().eq(true, BusDept::getCompanyId, companyId).like(BusDept::getDeptCode, deptCode));
    }

    @Override
    public BusDept getByDeptNo(String deptNo, Long companyId) {
        return getOne(new QueryWrapper<BusDept>().lambda().eq(true, BusDept::getCompanyId, companyId).eq(BusDept::getDeptNo, deptNo));
    }

    @Override
    public void syncHyData(OpenUser openUser) {
        Long companyId = openUser.getCompanyId();
        SysCompany company = companyService.getById(companyId);
        if (FlymeUtils.isNotEmpty(company)) {
            String dbName = company.getBusinessScope();
            ApiAssert.isNotEmpty("账套实例未配置", dbName);
            List<EntityMap> deptList = hyRemoteOrderService.selectHyDeptList(dbName);
            for (EntityMap entityMap : deptList) {
                //海鹰部门编码
                String hyDeptNo = entityMap.get("deptNo");
                String deptName = entityMap.get("deptName");
                String orderNum = entityMap.get("orderNum");
                String deptCode = entityMap.get("deptCode");
                //TODO 管理仓库名称
                String manageStore = entityMap.get("manageStore");
                BusDept dept = getByDeptName(deptName);
                if (FlymeUtils.isEmpty(dept)) {
                    dept = new BusDept();
                    dept.setOrganizationId(OpenHelper.getOrganizationId());
                    dept.setDeptState(CommonConstants.ENABLED);
                    dept.setDeptName(deptName);
                    dept.setCompanyId(5L);
                    dept.setDeptNo(deptCode);
                    dept.setOrderNum(orderNum);
                    save(dept);
                } else {
                    dept.setDeptNo(deptCode);
                    dept.setDeptName(deptName);
                    dept.setOrderNum(orderNum);
                    updateById(dept);
                }
                //保存部门中间表数据
                BusDeptHy deptHy = deptHyService.getByHyDeptId(hyDeptNo, companyId);
                if (FlymeUtils.isEmpty(deptHy)) {
                    deptHy = new BusDeptHy();
                    deptHy.setDeptId(dept.getDeptId());
                    deptHy.setCompanyId(companyId);
                    deptHy.setHyDeptNo(hyDeptNo);
                    deptHy.setHyDeptCode(deptCode);
                    deptHy.setHyDeptState(CommonConstants.ENABLED);
                    deptHy.setHyDeptName(deptName);
                    deptHyService.save(deptHy);
                } else {
                    deptHy.setHyDeptName(deptName);
                    deptHyService.updateById(deptHy);
                }

            }
        }
    }
}
